<?php

namespace App\Http\Controllers;

use App\ServicesNew\ProductSkuService;
use App\ServicesNew\StockService;
use App\Utils\Assert;
use App\VO\Stock\MetaInfo\StockFactory;
use App\VO\Stock\StockLastServiceAbleVO;
use Carbon\Carbon;
use Illuminate\Http\Request;

/**
 * 库存服务
 * Class StockController
 * @package App\Http\Controllers
 */
class StockController extends BaseController
{
    /**
     * @api {get} /stock 产品库存
     * @apiGroup Stock
     *
     * @apiParam {Number} productSkuId  skuID
     * @apiParam {String} date  日期，格式 2020-09-09
     */
    /**
     * @param Request $request
     * @param ProductSkuService $productSkuService
     * @param StockService $stockService
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function index(Request $request, ProductSkuService $productSkuService, StockService $stockService)
    {
        $cityId = $this->getUserLocationCityId();

        $productSkuId = $request->input('productSkuId');
        $date = $request->input('date');

        $productSkuEntity = $productSkuService->getProductSkuEntityById($productSkuId);
        Assert::notNull($productSkuEntity);

        $timePeriodArr = $stockService->getTimePeriodArr(Carbon::parse($date)->toDateString(), $cityId, $productSkuEntity->getProductId());
        return $this->successJsonResult(['periods' => $timePeriodArr]);
    }

    /**
     * @api {get} /stock/lastServiceAbleDateTime/{productSkuId}  获取产品最近可以下单的时间
     * @apiGroup Stock
     */
    /**
     * @param int $productSkuId
     * @param ProductSkuService $productSkuService
     * @param StockService $stockService
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function lastServiceAbleDateTime(int $productSkuId, ProductSkuService $productSkuService, StockService $stockService)
    {
        $productSkuEntity = $productSkuService->getProductSkuEntityById($productSkuId);
        Assert::notNull($productSkuEntity);

        $lastServiceAbleDateTime = $stockService->getLastServiceAbleDateTimeByProductSkuEntity($productSkuEntity);
        Assert::notNull($lastServiceAbleDateTime);

        $stockLastServiceAbleVO = new StockLastServiceAbleVO();
        $stockLastServiceAbleVO->setLastServiceAbleDateTime(StockFactory::getServiceDateTimeInfo($lastServiceAbleDateTime));

        return $this->successJsonResult($stockLastServiceAbleVO);
    }
}
